package cn.fz.learn02.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 原文链接：https://blog.csdn.net/jiang_wang01/article/details/134202532
 */
@RestController
@Slf4j
@RequestMapping("order")
public class OrderController {
    private static final ConcurrentHashMap<String, DeferredResult<String>> DEFERRED_RESULT = new ConcurrentHashMap<>();

    // public static ConcurrentHashMap<String, DeferredResult<String>> getDeferredResult() {
    //     return DEFERRED_RESULT;
    // }
    //
    // public static void setDeferredResult(ConcurrentHashMap<String, DeferredResult<String>> deferredResult) {
    //     DEFERRED_RESULT = deferredResult;
    // }

    /**
     * 查询订单支付结果
     *
     * @param orderId 订单编号
     * @return DeferredResult
     */
    @GetMapping("queryOrderPayResult")
    public DeferredResult<String> queryOrderPayResult(@RequestParam("orderId") String orderId) {
        log.info("订单orderId:[{}]发起了支付", orderId);
        // 5s 超时
        DeferredResult<String> result = new DeferredResult<>(5000L);
        // 超时操作
        result.onTimeout(() -> DEFERRED_RESULT.get(orderId).setResult("超时了"));
        // 完成操作
        result.onCompletion(() -> DEFERRED_RESULT.remove(orderId));
        // 保存此 DeferredResult 的结果
        DEFERRED_RESULT.put(orderId, result);
        return result;
    }

    /**
     * 支付回调
     *
     * @param orderId 订单id
     * @return 支付回调结果
     */
    @GetMapping("payNotify")
    public String payNotify(@RequestParam("orderId") String orderId) {
        if (DEFERRED_RESULT.containsKey(orderId)){
            Optional.ofNullable(DEFERRED_RESULT.get(orderId)).ifPresent(result->result.setResult("完成支付"));
            // 设置之前orderId toPay请求的结果
            return "回调处理成功";
        }
        return "回调处理失败";
    }
}
